<?php

require_once 'q/dao.php';
require_once 'config/db.php';


class dao_admin_user extends q_dao {

    private $roles = array(
        'admin'     => 10, // edit admin
        'editor'    => 20, // edit game
        'censor'    => 30, // delete comment
        'user'      => 50, // allow login
    );

    private static $_instance = null;

    public static function getInstance(){
        if(!self::$_instance){
            self::$_instance = new dao_admin_user();
        }
        return self::$_instance;
    }

    /**
     * @return int uid or false on error
     */
    public function check($username, $password_md5){
        $db = $this->_getdb(config_db::get('admin'));
        $sql = "select uid from admin_user"
            . " where `name` = '".$db->escape($username)."' and `passwd` = '".$db->escape($password_md5)."' "
            . " limit 1";

        return $db->query_one($sql);
    }

    /**
     * @return int uid
     */
    public function create($username, $password){

    }

    public function delete($uid){

    }

     public function changepw($uid, $password_md5, $new_password_md5){
        $db = $this->_getdb(config_db::get('admin'));
        $sql = "select uid from admin_user"
            . " where `uid` = '".$db->escape($uid)."' and `passwd` = '".$db->escape($password_md5)."' "
            . " limit 1";

        $uid = $db->query_one($sql);
        if(empty($uid)){
            return false;
        }

        $sql = "update admin_user "
            . " set passwd = '".$db->escape($new_password_md5)."' "
            . " where uid = '".$db->escape($uid)."' "
            . " limit 1 ";

        return $db->query($sql);
    }


    /**
     * @return bool 
     */
    public function check_role($uid, $needed_role){
        if(empty($this->roles[$needed_role])){
            error_log('bad role for check: '.$uid.', '.$needed_role);
            return false;
        }

        $user_role = $this->get_role($uid);
        $user_role_rank = $this->roles[$user_role];
        $need_role_rank = $this->roles[$needed_role];
        if($user_role_rank <= $need_role_rank){
            return true;
        }

        return false;
    }

    public function get_role($uid){
        $db = $this->_getdb(config_db::get('admin'));
        $sql = "select role from admin_user"
            . " where `uid` = '".$db->escape($uid)."' "
            . " limit 1";

        return $db->query_one($sql);
    }

    public function set_role($uid, $role){
        if(!in_array($role, $this->roles)){
            echo 'bad role for check';
            exit;
        }

    }

}

